package com.micro.magupe.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

import com.micro.magupe.gateway.security.CustomRemoteTokenServices;
import com.micro.magupe.gateway.security.PermitAllUrlProperties;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    private ResourceServerProperties resource;
    
    @Bean
    public PermitAllUrlProperties getPermitAllUrlProperties() {
        return new PermitAllUrlProperties();
    }
    
	@Override
    public void configure(HttpSecurity http) throws Exception {
        http
        	.csrf().disable()
        	.requestMatchers().antMatchers("/**")
        	.and()
        	.requestMatchers().antMatchers("/actuator/hystrix.stream")
        	.and()
        	.headers().frameOptions().disable()
        	.and()
        	.authorizeRequests()
        	.antMatchers(getPermitAllUrlProperties().getPermitall()).permitAll()
        	.anyRequest().authenticated();
    }
	
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    	resources.resourceId("micro-magupe-auth").stateless(true);
    	
        CustomRemoteTokenServices resourceServerTokenServices = new CustomRemoteTokenServices();
        resourceServerTokenServices.setCheckTokenEndpointUrl(resource.getTokenInfoUri());
        resourceServerTokenServices.setClientId(resource.getClientId());
        resourceServerTokenServices.setClientSecret(resource.getClientSecret());
        resources.tokenServices(resourceServerTokenServices);
    }
}
